package com.kaishengit.dao;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

import com.kaishengit.entity.Employee;
import com.kaishengit.entity.Goal;
import com.kaishengit.util.DBHelp;
import com.kaishengit.util.RowMapper;

public class GoalDao {
	private DBHelp<Goal> db = new DBHelp<Goal>();
	public List<Goal> findListByProjectId(String projectid) {
		StringBuilder sql = new StringBuilder();
		sql.append("SELECT employeeid,projectid,te.username,te.password,te.pic,");
		sql.append("te.email,tg.id,tg.name,tg.desc,tg.createtime ,tg.rate FROM t_goal AS tg ");
		sql.append("LEFT JOIN t_employee AS te ON te.id = tg.employeeid ");
		sql.append("WHERE tg.projectid = ?");
		
		return db.executeQueryForList(sql.toString() ,new GoalRowMapper(),projectid);
	}
	public Goal findGoalByGoalId(String id) {
		StringBuilder sql = new StringBuilder();
		sql.append("SELECT employeeid,projectid,te.username,te.password,te.pic,");
		sql.append("te.email,tg.id,tg.name,tg.desc,tg.createtime ,tg.rate FROM t_goal AS tg ");
		sql.append("LEFT JOIN t_employee AS te ON te.id = tg.employeeid ");
		sql.append("WHERE tg.id = ?");
		return db.executeQueryForObject(sql.toString() ,new GoalRowMapper(),id);
	}
	public boolean editGoal(String id, String name, String desc) {
		String sql = "update t_goal set `name` = ?,`desc` = ? where id = ?";
		return db.executeSQL(sql, name,desc,id);
	}
	public boolean addGoal(Goal goal) {
		String sql = "insert into t_goal(id,`name`,`desc`,createtime,employeeid,projectid,rate) values(?,?,?,?,?,?,?)";
		return db.executeSQL(sql, goal.getId(),goal.getName(),goal.getDesc(),goal.getCreatetime(),goal.getEmployeeid(),goal.getProjectid(),goal.getRate());
	}
	
	
	
	
	private class GoalRowMapper implements RowMapper<Goal>{

		public Goal mapRow(ResultSet rs) throws SQLException {
			Goal g = new Goal();
			g.setCreatetime(rs.getString("createtime"));
			g.setDesc(rs.getString("desc"));
			g.setEmployeeid(rs.getString("employeeid"));
			g.setId(rs.getString("id"));
			g.setName(rs.getString("name"));
			g.setProjectid(rs.getString("projectid"));
			g.setRate(rs.getInt("rate"));
			Employee e = new Employee();
			e.setEmail(rs.getString("email"));
			e.setId(rs.getString("employeeid"));
			e.setPassword(rs.getString("password"));
			e.setPic(rs.getString("pic"));
			e.setUsername(rs.getString("username"));
			g.setEmployee(e);
			
			return g;
		}
		
	}

	

	
}
